package com.seres.math;

import java.util.Iterator;
import java.util.List;

import com.seres.data.Index;
import com.seres.data.Stakeholder;

public class STICalculator {
	private static final int MIN_RESCALED = 0;
	private static final int MAX_RESCALED = 20;
	
	public IndexEthicalStatus calcNewSTIStatus(Index sti, List<StakeholderEthicalStatus> shStatus, float minimumStatusValue, float maximumStatusValue, List<Stakeholder> stakeholders){
		float newValue = 0;
		int totalWeightingFactorsSTI = calcTotalWeightingFactorsSTI(stakeholders);
		
		Iterator<StakeholderEthicalStatus> it = shStatus.iterator();
//		System.out.println("*** sti calculator begin ***");
		while(it.hasNext()){
			StakeholderEthicalStatus status = it.next();
			newValue += ((float) status.getStakeholder().getWeightingFactorSTI()/totalWeightingFactorsSTI) * status.getValue();
//			System.out.println("status.getValue(): " + status.getValue());
//			System.out.println("newValue: " + newValue);
		}
//		System.out.println("newValue: " + newValue);
		newValue = rescale(newValue,minimumStatusValue,maximumStatusValue,MIN_RESCALED,MAX_RESCALED);
		newValue = newValue/MAX_RESCALED;
//		System.out.println("newValue: " + newValue);
//		System.out.println("*** sti calculator end ***");
		return new IndexEthicalStatus(newValue, sti);
		
	}
	
	private int calcTotalWeightingFactorsSTI(List<Stakeholder> stakeholders){
		int total = 0;
//		Stakeholder[] values = Stakeholder.values();
		for(int i = 0; i < stakeholders.size(); i++){
			total += stakeholders.get(i).getWeightingFactorSTI();
		}
		return total;
	}
	private float rescale(float x, float minOldScale, float maxOldScale, int minNewScale, int maxNewScale){
		return ((maxNewScale-minNewScale)/(maxOldScale-minOldScale)) * (x - minOldScale) + minNewScale;
	}
}
